package org.papervision3d.core.proto
{
	import org.papervision3d.core.Number3D;
	import org.papervision3d.core.geom.Face3D;
	import org.papervision3d.core.geom.Mesh3D;
	import org.papervision3d.core.geom.Vertex3D;
	import org.papervision3d.objects.DisplayObject3D;
	import org.papervision3d.core.geom.DrawTriangle;
	import org.papervision3d.core.Matrix3D;
	
	public class BoundsCallBack extends TraverseCallback
	{
		
		public var min : Number3D;
		public var max : Number3D;
		
		public function BoundsCallBack()
		{
			super();
			min = new Number3D(Infinity, Infinity, Infinity );
			max = new Number3D(-Infinity, -Infinity, -Infinity );
		}
		
		
		override public function enter(node:DisplayObject3D):Boolean
        {
        //	trace( node.name );
        	curpath.push(node);
            return true;
        }
		override public function leave(node:DisplayObject3D):void
        {
        	curpath.pop();
        }
        
        override protected function inclip(triangle:DrawTriangle):Boolean
        {
            return true;
        }
		
		override public function face(face:Face3D, object:Mesh3D):void {
			
			var v0 : Vertex3D = new Vertex3D( face.v0.x, face.v0.y, face.v0.z );
        	/* var v1 : Vertex3D = new Vertex3D( face.v1.x, face.v1.y, face.v1.z );
        	var v2 : Vertex3D = new Vertex3D( face.v2.x, face.v2.y, face.v2.z );
        	 */
        	var i : int = curpath.length;
        	while( --i >-1 ) {
        		localeToParentTransform(v0, curpath[i] );
        		/* localeToParentTransform(v1, curpath[i] );
        		localeToParentTransform(v2, curpath[i] ); */
        	}
        	
        	
        	
			min.x = Math.min( min.x, v0.x );
			min.y = Math.min( min.y, v0.y );
			min.z = Math.min( min.z, v0.z );
            max.x = Math.max( max.x, v0.x );
			max.y = Math.max( max.y, v0.y );
			max.z = Math.max( max.z, v0.z );
		}
		
		private function localeToParentTransform( v : Vertex3D, parent : DisplayObject3D ) : void {
			var m:Matrix3D = parent.transform;
    		
    		//trace( "localeToParentTransform  : "+parent );
           
            var vx:Number = v.x;
            var vy:Number = v.y;
            var vz:Number = v.z;

            var sx:Number = vx * m.n11 + vy * m.n12 + vz * m.n13 + m.n14;
            var sy:Number = vx * m.n21 + vy * m.n22 + vz * m.n23 + m.n24;
            var sz:Number = vx * m.n31 + vy * m.n32 + vz * m.n33 + m.n34;

			v.x = sx;
			v.y = sy;
			v.z = sz;
    		//trace("  		", v.x, v.y, v.z );
		}
		
		
		protected var curpath:Array = new Array();
	}
}